package com.bawei.android_mianshi

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.Toast
import com.bawei.android_mianshi.service.OneService
import com.bawei.android_mianshi.service.ThreeIntentService
import com.bawei.android_mianshi.service.TwoService
import kotlin.math.log

/**
 * 1。Service的2种启动方式 重点
 * 2。前台服务
 * 3.service和activity通信方式：广播+绑定服务
 * 4。IntentService：是Service子类，专门用于网路请求服务
 *
 *
 *
 */
class MainActivity2 : AppCompatActivity() {
    //和服务建立的链接
    private var serviceConnection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.d("TwoService", "和服务建立了链接: ")
            var twoBinder = service as TwoService.TwoBinder
            twoBinder.jiehun()//调用服务中的方法
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d("TwoService", "和服务断开了链接: ")

        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

    }
    //启动服务
    fun start(view: View) {
        var intent = Intent(this,OneService::class.java)
        startService(intent)
    }
    //停止服务
    fun stop(view: View) {
        var intent = Intent(this,OneService::class.java)
        stopService(intent)
    }
    //绑定服务
    fun bind(view: View) {
        var intent = Intent(this, TwoService::class.java)
        bindService(intent,serviceConnection,Service.BIND_AUTO_CREATE)//绑定成功时候自动创建Service

    }
    //解绑服务：判断服务是否绑定
    fun unbind(view: View) {
        unbindService(serviceConnection)
    }
    //启动IntentService
    fun startIntent(view: View) {
        var intent = Intent(this,ThreeIntentService::class.java)
        startService(intent)
    }
}